import React, { useState } from 'react';
import s from './style.module.css';
import { Input, Button, Checkbox, Form, Message, Dialog, Progress } from '@knownsec/react-component';
import recursionForm from '@/common/recursionForm';
import { backupActive,backupProgress } from '~/API';
import i from '@/index.module.css';
import cn from 'classnames';
import { deepClone } from '@/common/constant.js';

const defaultData = {
  url: '',
  is_auth_enabled: false,
  auth_user: '',
  auth_password: '',
  sha1: '',
};

export default function WhiteSite() {
  const [form] = Form.useForm();
  const [disInp, setDisInp] = useState(true);
  const [upVisible, setUpVisible] = useState(false);
  let [percent, setPercent] = useState(0);
  let timer = null;
  let setIn = null;
  const createForm = React.useRef();
  const validatormap = (rule, value) => {
    const reg = new RegExp(
      '^(((http|ftp)://)|(www.))+(([a-zA-Z0-9._-]+.[a-zA-Z]{2,6})|([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}))(/[a-zA-Z0-9&%_./-~-]*)?$'
    );
    if (rule.field == 'url' && !reg.test(value)) {
      return Promise.reject('请输入合法的URL');
    } else if (rule.field == 'sha1' && value.length < 40) {
      return Promise.reject(`确保该值不少于40个字符(现在有${value.length}个)`);
    } else if (rule.field == 'auth_user' && !disInp && (!value || value.length > 20)) {
      return Promise.reject(`确保该值不多于20个字符(现在有${value.length}个)`);
    } else if (rule.field == 'auth_password' && !disInp && (!value || value.length > 30)) {
      return Promise.reject(`确保该值不多于30个字符(现在有${value.length}个)`);
    } else {
      return Promise.resolve();
    }
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    createForm.current.setFieldsValue(values);
    !values.is_auth_enabled && form.validateFields(['auth_password', 'auth_user']);
    setDisInp(!form.getFieldsValue().is_auth_enabled);
  };
  const onsub = () => {
    createForm.current.validateFields().then(async (res) => {
      let res_ = deepClone(res);
      if (!res.is_auth_enabled) {
        delete res_.is_auth_enabled;
        delete res_.auth_user;
        delete res_.auth_password;
      }
      const resB= await backupActive(res_).catch((e)=>{return e});
      console.log('[ resB ]-58', resB)
      if(resB.status!== 'success'){
        let msg = '';
        if (resB.message) {
          msg = resB.message;
        } else {
          msg = Object.values(resB.data)[0];
        }
        Message.show({
          pro: true,
          showClose: false,
          type: 'error',
          message:msg,
        });
        return false;
      }
      setIn = setInterval(async () => {
        const pace = await backupProgress({kind:'backup'});
        setPercent(pace.data?.progress);
        if (pace.data.status == 2) {
          clearInterval(setIn);
          setPercent(100);
          setUpVisible(false);
          Message.show({
            pro: true,
            showClose: false,
            type: 'success',
            message:pace.message,
          });
        }else if (pace.data.status == 3) {
          clearInterval(setIn);
          setPercent(100);
          setUpVisible(false);
          Message.show({
            pro: true,
            showClose: false,
            type: 'error',
            message:pace.message,
          });
        }
      }, 2000);
    });
  };
  const changeVisible = () => {
    setUpVisible(false);
    setPercent(0);
    clearInterval(timer);
    clearInterval(setIn);
  };
  return (
    <div className={s.backForm}>
      <Form
        form={form}
        ref={createForm}
        initialValues={defaultData}
        name="control-ref"
        onValuesChange={(newItem, allValues) => {
          onValues(newItem, allValues);
        }}
      >
        <Form.Item
          name="url"
          label="数据地址"
          valuePropName="value"
          className={s.item}
          rules={[{ required: true, validator: validatormap }]}
        >
          <Input
            pro
            className={s.w_30}
            placeholder="请输入FTP/HTTP的全路径"
            type="text"
            autoComplete={'off'}
          />
        </Form.Item>
        <Form.Item
          label="预登录认证"
          name="is_auth_enabled"
          className={s.item}
          valuePropName="checked"
          rules={[{ required: false, validator: validatormap }]}
        >
          <Checkbox>只支持基本HTTP/FTP认证</Checkbox>
        </Form.Item>
        <Form.Item
          name="auth_user"
          label="认证用户"
          valuePropName="value"
          className={s.item}
          rules={[{ required: false, validator: validatormap }]}
        >
          <Input
            pro
            className={s.w_30}
            disabled={disInp}
            placeholder="请输入认证用户名"
            type="text"
            autoComplete={'off'}
          />
        </Form.Item>
        <Form.Item
          name="auth_password"
          label="认证密码"
          valuePropName="value"
          className={s.item}
          rules={[{ required: false, validator: validatormap }]}
        >
          <Input
            pro
            className={s.w_30}
            disabled={disInp}
            placeholder="请输入认证密码"
            type="text"
            autoComplete={'off'}
          />
        </Form.Item>
        <Form.Item
          name="sha1"
          label="sha1对比"
          valuePropName="value"
          className={s.item}
          rules={[{ required: true, validator: validatormap }]}
        >
          <Input
            pro
            className={s.w_30}
            placeholder="请输入备份文件的sha1对比值"
            type="text"
            autoComplete={'off'}
          />
        </Form.Item>
        <div className={s.btn}>
          <Button pro type="primary" onClick={onsub}>
            确定上传
          </Button>
        </div>
      </Form>
      <Dialog
        className={cn(i.w400)}
        title="备份文件上传"
        visible={upVisible}
        cancelText=""
        confirmText=""
        onhide={() => {
          changeVisible();
        }}
      >
        <div className={i.p20}>
          <p className={cn(i.tac)}>正在进行{upVisible}</p>
          <p className={cn(i.tac)}>进度:{percent}%</p>
          <Progress percent={percent + '%'} className={i.mt10} />
        </div>
      </Dialog>
    </div>
  );
}
